
import 'dart:async';

import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import 'package:rfid/page/borrow_result_page.dart';
import 'package:rfid/util/toast_util.dart';
import '../entity/current_task_entity.dart';
import '../entity/setting_entity.dart';
import '../event/lock_state_event.dart';
import '../main.dart';
import '../util/timer_manager.dart';
import '../widget/auth_dialog.dart';
import '../widget/device_name_widget.dart';
import 'help_page.dart';


class SearchDoor extends StatefulWidget {
  const SearchDoor({Key? key}) : super(key: key);

  @override
  State<SearchDoor> createState() => _SearchDoorState();
}

class _SearchDoorState extends State<SearchDoor> {



  late List<SettingEntityReader> _lists;
  final RxList<SettingEntityReader> _list = RxList();
  var _doorNo = "";
  var pageIndex = 1;
  var pageSize = 32;

  StreamSubscription? lockSubscription;

  var isBorrow = true;


  @override
  initState() {
    super.initState();
    isBorrow = Get.arguments;
    lockSubscription = eventFactory.on<LockStateEvent>().listen((event) {
      if(event.state == 1 && currentTask.uid != null){
        Get.to(() => const BorrowResult());
      }
    });

    if(settingEntity.reader != null && settingEntity.reader!.isNotEmpty){
      _lists = settingEntity.reader!.where((element) => element.state == 0).toList();

      _subList();
    }else{
      toastWarn('未配置格口');
    }

    WidgetsBinding.instance.addPostFrameCallback((_){
      tts.speak("请选择格口");

      timer.startCountDown(CountDownMode.normal,(){
        // if(Get.isDialogOpen != null && Get.isDialogOpen!){
        //   Get.back();
        // }
        // Get.back();
        Get.until((route) => route.isFirst);
      });
    });

  }



  @override
  void dispose() {

    lockSubscription?.cancel();
    lockSubscription = null;
    super.dispose();
  }

  _subList(){

    if(pageIndex<1){
      pageIndex = 1;
      toastWarn('已经是第一页');
    }
    if(_lists.length > pageIndex*pageSize){
      // list.toList().clear();
      _list.clear();
      _list.addAll(_lists.sublist((pageIndex-1)*pageSize,pageIndex*pageSize));
    }else if(_lists.length <= pageIndex*pageSize && _lists.length > (pageIndex-1)*pageSize){
      _list.clear();
      _list.addAll(_lists.sublist((pageIndex-1)*pageSize,_lists.length));
    }else{
      pageIndex--;
      toastWarn('已经是最后一页');
    }

  }


  _appBar(){
    return Container(
      width: double.infinity,
      height: 42.h,
      alignment: Alignment.center,
      padding: const EdgeInsets.only(left: 20,right: 20).w,
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        crossAxisAlignment: CrossAxisAlignment.center,
        children: [
          deviceNameWidget(),
          InkWell(
            onTap: (){
              Get.to(()=> const Help());
            },
            child:  Row(
              crossAxisAlignment: CrossAxisAlignment.center,
              children: [
                Icon(Icons.help,color: Colors.white,size: 20.sp,),
                Text(" 帮助",style: TextStyle(color: Colors.white,fontSize: 12.sp),)
              ],
            ),
          )

        ],
      ),
    );
  }

  _title(){
    return Container(
      margin: EdgeInsets.only(top: 20.h,left: 20.w,right: 20.w),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        crossAxisAlignment: CrossAxisAlignment.center,
        children: [
          InkWell(
            onTap: (){
              timer.cancel();
              Get.back();
            },
            child: _image("assets/images/back.png",60.w,23.h),
          ),
          _image("assets/images/type_door_title.jpg",90.w,21.h),
          Obx(() => Text("${timer.normalTime.value}s",style: TextStyle(color: Colors.white,fontSize: 12.sp),))
        ],
      )
    );
  }

  _searchBarWidget(){
    return Container(
      decoration:BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.all(Radius.circular(16.r)),
      ),
      padding: EdgeInsets.only(left: 10.w,right: 10.w,top: 2.h,bottom: 2.h),
      margin:  EdgeInsets.only(left: 20.w, right: 20.w, bottom: 15.h,top: 15.h),
      child: IntrinsicHeight(
        child: Row(
          children: [
            _image("assets/images/search_icon.png",18.w,18.h),
            SizedBox(width: 4.w,),
            Container(
              width: 240.w,
              child:TextField(
                  minLines: 1,
                  keyboardType: TextInputType.number,
                  textInputAction: TextInputAction.search,
                  onChanged: (input){
                    _doorNo = input;
                  },
                  decoration: const InputDecoration(
                    isCollapsed: true,
                    border: InputBorder.none,
                    hintText: "输入格口号打开指定格口",
                  ),

                  style: TextStyle(color: Colors.black,fontSize: 12.sp)
              )
            ),
            const VerticalDivider(),
            TextButton(onPressed: () {
              try{
                var door = _list.firstWhere((element) => element.doorNo == _doorNo);
                setTask(door);
              }catch(e){
                toastWarn('格口不存在');
              }

            }, child: Text('打开',style: TextStyle(fontSize: 12.sp),)),
          ],
        ),
      )
    );
  }

  setTask(SettingEntityReader reader){
    currentTask.task = Task.borrowWithDoor;
    currentTask.readerIp = reader.readerIp;
    currentTask.addr = reader.addr;
    currentTask.lock = reader.lock;
    currentTask.ant = reader.ant;
    currentTask.doorNo = reader.doorNo;
    currentTask.needCheckCount = isBorrow;


    AuthDialog().authTypeDialog(callback: (){
      timer.startCountDown(CountDownMode.normal,(){
        if(Get.isDialogOpen != null && Get.isDialogOpen!){
          Get.back();
        }
      }, reset: false);
    });
  }



  _itemBuilder(index){
    var item = _list[index];
    return InkWell(
      onTap: (){
        setTask(item);
      },
      child: Stack(
        alignment: Alignment.center,
        children: [
          _image("assets/images/door_bg.png", 100.w, 70.h),
          Text('格口${item.doorNo}',style: TextStyle(color: Colors.blue,fontWeight:FontWeight.bold,fontSize: 8.sp),),
        ],
      ),
    );
  }

  _booksContainer(){
    return Container(
      margin: EdgeInsets.only(left: 20.w,right: 20.w),
      width: double.infinity,
      height: 440.h,

      child: Obx(() => GridView.builder(
        itemBuilder: (context, index) {
          return _itemBuilder(index);
        },
        itemCount: _list.length,
        gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(crossAxisCount: 4,childAspectRatio:1.42,  crossAxisSpacing: 5.w),
      ),)
    );
  }

  _action(){
    return Row(
      mainAxisAlignment: MainAxisAlignment.center,
      crossAxisAlignment: CrossAxisAlignment.center,
      children: [
        InkWell(
          onTap: (){
            pageIndex--;
            _subList();
          },
          child:  _image("assets/images/previous.png", 80.w, 36.h),
        ),
        InkWell(
          onTap: (){
            pageIndex++;
            _subList();
          },
          child:   _image("assets/images/next.png", 80.w, 36.h),
        )
      ],
    );
  }


  _image(name,width, height){
    return Image.asset(name,height: height, width: width, fit: BoxFit.fill,);
  }


  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Container(
        width: double.infinity,
        height: double.infinity,
        decoration: const BoxDecoration(
          image: DecorationImage(
            fit: BoxFit.fill,
            image: AssetImage(
              "assets/images/bg.png",
            ),
          ),
        ),
        child: Column(
          children: [
            _appBar(),
            _title(),
            _searchBarWidget(),
            _booksContainer(),
            _action(),
          ],
        ),
      ),
    );
  }
}

